package server

import (
	"dag2.0/gat1400-proxy/cache"
	"dag2.0/gat1400-proxy/context"
	"dag2.0/gat1400-proxy/logger"
	"dag2.0/gat1400-proxy/model"
	"dag2.0/gat1400-proxy/model/constant"
	"fmt"
	"time"
)

type Manager struct {
	ManagerID       string `json:"ManagerID"`
	UpIp            string `json:"ManagerIp"`
	UpPort          string `json:"ManagerPort"`
	UserName        string `json:"user_name"`
	Password        string `json:"password"`
	RegisterSuccess bool   `json:"registerSuccess"`
}

func RegisterAndKeepAliveAction() {
	cache.GetIns().SubscribeManagers.Range(func(key string, value interface{}) (shouldContinue bool) {
		if _, ok := value.(*model.SubscribeManagerEx); !ok {
			logger.LOG_ERROR(fmt.Sprintf("类型转换错误，需要*model.SubscribeManagerEx 类型，类型为:%T", value))
			return true
		}
		manager := value.(*model.SubscribeManagerEx)
		//只处理作为上级的订阅
		//视图库为上级（MANAGER_UP），表示此视图库的任务为上级订阅下级
		if manager.ManagerType != constant.MANAGER_UP {
			return true
		}
		if manager.IsRegister {
			return true
		}
		if manager.UserName == "" || manager.Password == "" {
			logger.LOG_DEBUG("用户名或密码为空，跳过注册")
			return true
		}
		//注册
		if context.GetBool("enable-register") {
			go manager.Register()
			//保活
			go manager.KeepAlive()
		}
		manager.IsRegister = true
		return true
	})
}

func RegisterAndKeepAlive() {
	go func() {
		for {
			time.Sleep(time.Second * time.Duration(30))
			RegisterAndKeepAliveAction()
		}
	}()
}
